package pkg

import (
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"time"

	"github.com/hashicorp/go-retryablehttp"
)

const (
	maxWaitTime = time.Second * 15
	retryMax    = 3
)

func GetRetryClient() *http.Client {
	retryClient := retryablehttp.NewClient()
	retryClient.RetryMax = retryMax
	retryClient.RetryWaitMax = maxWaitTime
	return retryClient.StandardClient()
}

func UtilGet(httpClient *http.Client, url string) (string, error) {
	resp, err := httpClient.Get(url)

	if err != nil {
		return "", err
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	if resp.StatusCode != 200 {
		return "", errors.New(fmt.Sprint("状态码非200，是", resp.StatusCode))
	}

	return string(body), nil
}

func UtilPOST(httpClient *http.Client, url, contentType string, bodyContent io.Reader) (string, error) {
	resp, err := httpClient.Post(url, contentType, bodyContent)

	if err != nil {
		return "", err
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	if resp.StatusCode != 200 {
		return "", errors.New(fmt.Sprint("状态码非200，是", resp.StatusCode))
	}

	return string(body), nil
}
func UtilPOSTForm(httpClient *http.Client, url string, bodyContent url.Values) (string, error) {
	// resp, err := httpClient.PostForm(url, bodyContent)
	resp, err := http.PostForm(url, bodyContent)
	if err != nil {
		return "", err
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	if resp.StatusCode != 200 {
		return "", errors.New(fmt.Sprint("状态码非200，是", resp.StatusCode))
	}

	return string(body), nil
}
